<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">实验室</label>
        <!-- <el-input v-model="query.labId" clearable placeholder="实验室" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" /> -->
        <el-select
          v-model="query.labId"
          placeholder="请选择实验室"
          style="width: 185px;"
          clearable
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in labs"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <!-- <label class="el-form-item-label">审核人员</label> -->
        <!-- <el-select
          v-model="query.auditorId"
          placeholder="请选择"
          style="width: 185px;"
          clearable
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option v-for="item in users" :key="item.id" :label="item.username" :value="item.id" />
        </el-select> -->
        <label class="el-form-item-label">预约人</label>
        <el-select
          v-model="query.userId"
          placeholder="请选择"
          style="width: 185px;"
          clearable
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in users"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
        <label class="el-form-item-label">状态</label>
        <el-select
          v-model="query.status"
          placeholder="请选择"
          style="width: 185px;"
          clearable
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />

      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="labName" label="实验室" />
        <el-table-column prop="times" label="预约时间段">
          <template slot-scope="scope">
            <div>{{ scope.row.times[0].start | formatDate }}</div>
            <div v-for="(item, i) in scope.row.times" :key="i">
              <span>{{ item.start | formatTime }}</span> -
              <span>{{ item.end | formatTime }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="userName" label="预约人" />
        <el-table-column prop="auditName" label="审核人" />
        <!-- <el-table-column prop="reason" label="审核备注" /> -->
        <el-table-column
          prop="status"
          label="状态"
          :formatter="formatterStatus"
        />
        <el-table-column
          v-if="checkPer(['admin', 'booking:edit', 'booking:del'])"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <!-- <udOperation
              :data="scope.row"
              :permission="permission"
            /> -->
            <template v-if="scope.row.status == 0">
              <el-button
                size="mini"
                type="primary"
                @click="approveDialog(true, scope.row)"
                >通过</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="approveDialog(false, scope.row)"
                >拒绝</el-button
              >
            </template>
            <template v-else>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="delApproveInfo(scope.row)"
              ></el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>

    <!-- 审批弹框 -->
    <approveDialog
      :is-agree="isAgree"
      :approve-dialog="isShowApproveDialog"
      @approve="isApprove"
      @close="isShowApproveDialog = false"
    />
  </div>
</template>

<script>
import approveDialog from "./components/approveDialog.vue";
import getAllUserAndLabs from "@/mixins/getAllUserAndLabs.js";
import crudBooking, {
  searchId,
  resolveAppointmentAPI,
  rejectAppointmentAPI,
  del
} from "@/api/booking";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import { mapState } from "vuex";

const defaultForm = {
  id: null,
  type: null,
  labId: null,
  status: null,
  auditorId: null,
  startAt: null,
  endAt: null,
  auditorStatus: null,
  labUseRecordId: null,
  reason: null,
  creatorId: null,
  createdAt: null,
  updatedAt: null,
  isDeleted: null
};
export default {
  name: "BookingAuth",
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    approveDialog
  },
  mixins: [presenter(), header(), form(defaultForm), crud(), getAllUserAndLabs],
  cruds() {
    return CRUD({
      title: "预约审批",
      url: "api/labBusyTime/queryLabBusyTimeSelf",
      idField: "id",
      sort: "id,desc",
      crudMethod: { ...crudBooking },
      optShow: {
        add: false,
        edit: false,
        del: false,
        download: true,
        reset: true
      }
    });
  },
  data() {
    return {
      permission: {
        add: ["admin", "booking:add"],
        edit: ["admin", "booking:edit"],
        del: ["admin", "booking:del"]
      },
      rules: {
        type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
        labId: [{ required: true, message: "实验室不能为空", trigger: "blur" }],
        auditorId: [
          { required: true, message: "审核人员不能为空", trigger: "blur" }
        ],
        startAt: [
          { required: true, message: "预约开始时点不能为空", trigger: "blur" }
        ],
        endAt: [
          { required: true, message: "预约结束时间不能为空", trigger: "blur" }
        ],
        creatorId: [
          { required: true, message: "预约人不能为空", trigger: "blur" }
        ]
      },
      queryTypeOptions: [
        { key: "type", display_name: "类型" },
        { key: "labId", display_name: "实验室" },
        { key: "status", display_name: "状态" },
        { key: "auditorId", display_name: "审核人员" },
        { key: "auditorStatus", display_name: "实验室管理员审核" },
        { key: "creatorId", display_name: "预约人" }
      ],
      isShowApproveDialog: false,
      isAgree: true,
      status: [
        {
          label: "待审批",
          value: 0
        },
        {
          label: "未通过",
          value: 1
        },
        {
          label: "已通过",
          value: 2
        },
        {
          label: "已取消",
          value: 3
        }
      ],
      currentInfo: {}
    };
  },
  created() {
    this.getLabs();
    this.getUsers();
  },
  computed: {
    ...mapState("hjuser", ["systemSearchInfoId"])
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    async [CRUD.HOOK.beforeRefresh]() {
      return true;
    },
    async [CRUD.HOOK.afterRefresh]() {
      if (this.systemSearchInfoId) {
        try {
          const res = await searchId({ id: this.systemSearchInfoId });
          this.crud.data = res.content;
        } finally {
          this.$store.commit("hjuser/updatedsystemSearchInfoId", "");
        }
      }
      this.crud.data = this.crud.data.map(item => ({
        ...item,
        times: JSON.parse(item.times)
      }));
      return true;
    },
    approveDialog(val, content) {
      val ? (this.isAgree = true) : (this.isAgree = false);
      this.currentInfo = content;
      this.isShowApproveDialog = true;
    },
    async isApprove(isAgree, note) {
      if (isAgree) {
        const res = await resolveAppointmentAPI(this.currentInfo.id);
        if (res == 1) {
          return this.$message.error("该时间段已被预约过，无法通过");
        }
        this.currentInfo.status = 2;
      } else {
        await rejectAppointmentAPI(this.currentInfo.id, note);
        this.currentInfo.status = 1;
      }
      this.isShowApproveDialog = false;
    },
    async delApproveInfo(row) {
      await del([row.id]);
      this.$message.success("删除成功");
      const res = await searchId({});
      this.crud.data = res.content;
      this.crud.data = this.crud.data.map(item => ({
        ...item,
        times: JSON.parse(item.times)
      }));
    },
    formatterStatus(row) {
      if (row.status == 0) {
        return "待审批";
      } else if (row.status == 1) {
        return "未通过";
      } else if (row.status == 2) {
        return "已通过";
      } else {
        return "已取消";
      }
    }
  }
};
</script>

<style scoped></style>
